1 var byteLength
= require( 'mediawiki.String' ).byteLength
,
2 UriProcessor
= require( './UriProcessor.js' ),
5 /* eslint no-underscore-dangle: "off" */
7 * Controller for the filters in Recent Changes
8 * @class mw.rcfilters.Controller
11 * @param {mw.rcfilters.dm.FiltersViewModel} filtersModel Filters view model
12 * @param {mw.rcfilters.dm.ChangesListViewModel} changesListModel Changes list view model
13 * @param {mw.rcfilters.dm.SavedQueriesModel} savedQueriesModel Saved queries model
14 * @param {Object} config Additional configuration
15 * @cfg {string} savedQueriesPreferenceName Where to save the saved queries
16 * @cfg {string} daysPreferenceName Preference name for the days filter
17 * @cfg {string} limitPreferenceName Preference name for the limit filter
18 * @cfg {string} collapsedPreferenceName Preference name for collapsing and showing
19 * the active filters area
20 * @cfg {boolean} [normalizeTarget] Dictates whether or not to go through the
21 * title normalization to separate title subpage/parts into the target= url
24 Controller
= function MwRcfiltersController( filtersModel
, changesListModel
, savedQueriesModel
, config
) {
25 this.filtersModel
= filtersModel
;
26 this.changesListModel
= changesListModel
;
27 this.savedQueriesModel
= savedQueriesModel
;
28 this.savedQueriesPreferenceName
= config
.savedQueriesPreferenceName
;
29 this.daysPreferenceName
= config
.daysPreferenceName
;
30 this.limitPreferenceName
= config
.limitPreferenceName
;
31 this.collapsedPreferenceName
= config
.collapsedPreferenceName
;
32 this.normalizeTarget
= !!config
.normalizeTarget
;
34 this.pollingRate
= require( './config.json' ).StructuredChangeFiltersLiveUpdatePollingRate
;
36 this.requestCounter
= {};
37 this.uriProcessor
= null;
38 this.initialized
= false;
39 this.wereSavedQueriesSaved
= false;
41 this.prevLoggedItems
= [];
43 this.FILTER_CHANGE
= 'filterChange';
44 this.SHOW_NEW_CHANGES
= 'showNewChanges';
45 this.LIVE_UPDATE
= 'liveUpdate';
49 OO
.initClass( Controller
);
52 * Initialize the filter and parameter states
54 * @param {Array} filterStructure Filter definition and structure for the model
55 * @param {Object} [namespaceStructure] Namespace definition
56 * @param {Object} [tagList] Tag definition
57 * @param {Object} [conditionalViews] Conditional view definition
59 Controller
.prototype.initialize = function ( filterStructure
, namespaceStructure
, tagList
, conditionalViews
) {
60 var parsedSavedQueries
, pieces
,
61 displayConfig
= mw
.config
.get( 'StructuredChangeFiltersDisplayConfig' ),
62 defaultSavedQueryExists
= mw
.config
.get( 'wgStructuredChangeFiltersDefaultSavedQueryExists' ),
64 views
= $.extend( true, {}, conditionalViews
),
69 if ( namespaceStructure
) {
71 // eslint-disable-next-line no-jquery/no-each-util
72 $.each( namespaceStructure
, function ( namespaceID
, label
) {
73 // Build and clean up the individual namespace items definition
76 label
: label
|| mw
.msg( 'blanknamespace' ),
79 mw
.Title
.isTalkNamespace( namespaceID
) ?
82 cssClass
: 'mw-changeslist-ns-' + namespaceID
87 title
: mw
.msg( 'namespaces' ),
90 // Group definition (single group)
91 name
: 'namespace', // parameter name is singular
92 type
: 'string_options',
93 title
: mw
.msg( 'namespaces' ),
94 labelPrefixKey
: { default: 'rcfilters-tag-prefix-namespace', inverted
: 'rcfilters-tag-prefix-namespace-inverted' },
115 title
: mw
.msg( 'rcfilters-view-tags' ),
118 // Group definition (single group)
119 name
: 'tagfilter', // Parameter name
120 type
: 'string_options',
121 title
: 'rcfilters-view-tags', // Message key
122 labelPrefixKey
: 'rcfilters-tag-prefix-tags',
130 // Add parameter range operations
135 type
: 'single_option',
136 title
: '', // Because it's a hidden group, this title actually appears nowhere
138 allowArbitrary
: true,
139 // FIXME: $.isNumeric is deprecated
140 validate
: $.isNumeric
,
142 min
: 0, // The server normalizes negative numbers to 0 results
145 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
146 default: mw
.user
.options
.get( this.limitPreferenceName
, displayConfig
.limitDefault
),
148 filters
: displayConfig
.limitArray
.map( function ( num
) {
149 return controller
._createFilterDataFromNumber( num
, num
);
154 type
: 'single_option',
155 title
: '', // Because it's a hidden group, this title actually appears nowhere
157 allowArbitrary
: true,
158 // FIXME: $.isNumeric is deprecated
159 validate
: $.isNumeric
,
162 max
: displayConfig
.maxDays
164 sortFunc: function ( a
, b
) { return Number( a
.name
) - Number( b
.name
); },
165 numToLabelFunc: function ( i
) {
166 return Number( i
) < 1 ?
167 ( Number( i
) * 24 ).toFixed( 2 ) :
170 default: mw
.user
.options
.get( this.daysPreferenceName
, displayConfig
.daysDefault
),
173 // Hours (1, 2, 6, 12)
174 0.04166, 0.0833, 0.25, 0.5
176 ].concat( displayConfig
.daysArray
)
177 .map( function ( num
) {
178 return controller
._createFilterDataFromNumber(
180 // Convert fractions of days to number of hours for the labels
181 num
< 1 ? Math
.round( num
* 24 ) : num
193 title
: '', // Because it's a hidden group, this title actually appears nowhere
199 default: String( mw
.user
.options
.get( 'usenewrc', 0 ) )
206 // Before we do anything, we need to see if we require additional items in the
207 // groups that have 'AllowArbitrary'. For the moment, those are only single_option
208 // groups; if we ever expand it, this might need further generalization:
209 // eslint-disable-next-line no-jquery/no-each-util
210 $.each( views
, function ( viewName
, viewData
) {
211 viewData
.groups
.forEach( function ( groupData
) {
212 var extraValues
= [];
213 if ( groupData
.allowArbitrary
) {
214 // If the value in the URI isn't in the group, add it
215 if ( uri
.query
[ groupData
.name
] !== undefined ) {
216 extraValues
.push( uri
.query
[ groupData
.name
] );
218 // If the default value isn't in the group, add it
219 if ( groupData
.default !== undefined ) {
220 extraValues
.push( String( groupData
.default ) );
222 controller
.addNumberValuesToGroup( groupData
, extraValues
);
227 // Initialize the model
228 this.filtersModel
.initializeFilters( filterStructure
, views
);
230 this.uriProcessor
= new UriProcessor(
232 { normalizeTarget
: this.normalizeTarget
}
235 if ( !mw
.user
.isAnon() ) {
237 parsedSavedQueries
= JSON
.parse( mw
.user
.options
.get( this.savedQueriesPreferenceName
) || '{}' );
239 parsedSavedQueries
= {};
242 // Initialize saved queries
243 this.savedQueriesModel
.initialize( parsedSavedQueries
);
244 if ( this.savedQueriesModel
.isConverted() ) {
245 // Since we know we converted, we're going to re-save
246 // the queries so they are now migrated to the new format
247 this._saveSavedQueries();
251 if ( defaultSavedQueryExists
) {
252 // This came from the server, meaning that we have a default
253 // saved query, but the server could not load it, probably because
254 // it was pre-conversion to the new format.
255 // We need to load this query again
256 this.applySavedQuery( this.savedQueriesModel
.getDefault() );
258 // There are either recognized parameters in the URL
259 // or there are none, but there is also no default
260 // saved query (so defaults are from the backend)
261 // We want to update the state but not fetch results
263 this.updateStateFromUrl( false );
265 pieces
= this._extractChangesListInfo( $( '#mw-content-text' ) );
267 // Update the changes list with the existing data
268 // so it gets processed
269 this.changesListModel
.update(
272 pieces
.noResultsDetails
,
273 true // We're using existing DOM elements
277 this.initialized
= true;
278 this.switchView( 'default' );
280 if ( this.pollingRate
) {
281 this._scheduleLiveUpdate();
286 * Check if the controller has finished initializing.
287 * @return {boolean} Controller is initialized
289 Controller
.prototype.isInitialized = function () {
290 return this.initialized
;
294 * Extracts information from the changes list DOM
296 * @param {jQuery} $root Root DOM to find children from
297 * @param {boolean} [statusCode] Server response status code
298 * @return {Object} Information about changes list
299 * @return {Object|string} return.changes Changes list, or 'NO_RESULTS' if there are no results
300 * (either normally or as an error)
301 * @return {string} [return.noResultsDetails] 'NO_RESULTS_NORMAL' for a normal 0-result set,
302 * 'NO_RESULTS_TIMEOUT' for no results due to a timeout, or omitted for more than 0 results
303 * @return {jQuery} return.fieldset Fieldset
305 Controller
.prototype._extractChangesListInfo = function ( $root
, statusCode
) {
307 $changesListContents
= $root
.find( '.mw-changeslist' ).first().contents(),
308 areResults
= !!$changesListContents
.length
,
309 checkForLogout
= !areResults
&& statusCode
=== 200;
311 // We check if user logged out on different tab/browser or the session has expired.
312 // 205 status code returned from the server, which indicates that we need to reload the page
313 // is not usable on WL page, because we get redirected to login page, which gives 200 OK
314 // status code (if everything else goes well).
316 if ( checkForLogout
&& !!$root
.find( '#wpName1' ).length
) {
317 location
.reload( false );
322 changes
: $changesListContents
.length
? $changesListContents
: 'NO_RESULTS',
323 fieldset
: $root
.find( 'fieldset.cloptions' ).first()
327 if ( $root
.find( '.mw-changeslist-timeout' ).length
) {
328 info
.noResultsDetails
= 'NO_RESULTS_TIMEOUT';
329 } else if ( $root
.find( '.mw-changeslist-notargetpage' ).length
) {
330 info
.noResultsDetails
= 'NO_RESULTS_NO_TARGET_PAGE';
331 } else if ( $root
.find( '.mw-changeslist-invalidtargetpage' ).length
) {
332 info
.noResultsDetails
= 'NO_RESULTS_INVALID_TARGET_PAGE';
334 info
.noResultsDetails
= 'NO_RESULTS_NORMAL';
342 * Create filter data from a number, for the filters that are numerical value
344 * @param {number} num Number
345 * @param {number} numForDisplay Number for the label
346 * @return {Object} Filter data
348 Controller
.prototype._createFilterDataFromNumber = function ( num
, numForDisplay
) {
351 label
: mw
.language
.convertNumber( numForDisplay
)
356 * Add an arbitrary values to groups that allow arbitrary values
358 * @param {Object} groupData Group data
359 * @param {string|string[]} arbitraryValues An array of arbitrary values to add to the group
361 Controller
.prototype.addNumberValuesToGroup = function ( groupData
, arbitraryValues
) {
362 var controller
= this,
363 normalizeWithinRange = function ( range
, val
) {
364 if ( val
< range
.min
) {
365 return range
.min
; // Min
366 } else if ( val
>= range
.max
) {
367 return range
.max
; // Max
372 arbitraryValues
= Array
.isArray( arbitraryValues
) ? arbitraryValues
: [ arbitraryValues
];
374 // Normalize the arbitrary values and the default value for a range
375 if ( groupData
.range
) {
376 arbitraryValues
= arbitraryValues
.map( function ( val
) {
377 return normalizeWithinRange( groupData
.range
, val
);
380 // Normalize the default, since that's user defined
381 if ( groupData
.default !== undefined ) {
382 groupData
.default = String( normalizeWithinRange( groupData
.range
, groupData
.default ) );
386 // This is only true for single_option group
387 // We assume these are the only groups that will allow for
388 // arbitrary, since it doesn't make any sense for the other
390 arbitraryValues
.forEach( function ( val
) {
392 // If the group allows for arbitrary data
393 groupData
.allowArbitrary
&&
394 // and it is single_option (or string_options, but we
395 // don't have cases of those yet, nor do we plan to)
396 groupData
.type
=== 'single_option' &&
397 // and, if there is a validate method and it passes on
399 ( !groupData
.validate
|| groupData
.validate( val
) ) &&
400 // but if that value isn't already in the definition
402 .map( function ( filterData
) {
403 return String( filterData
.name
);
405 .indexOf( String( val
) ) === -1
407 // Add the filter information
408 groupData
.filters
.push( controller
._createFilterDataFromNumber(
410 groupData
.numToLabelFunc
?
411 groupData
.numToLabelFunc( val
) :
415 // If there's a sort function set up, re-sort the values
416 if ( groupData
.sortFunc
) {
417 groupData
.filters
.sort( groupData
.sortFunc
);
424 * Reset to default filters
426 Controller
.prototype.resetToDefaults = function () {
427 var params
= this._getDefaultParams();
428 if ( this.applyParamChange( params
) ) {
429 // Only update the changes list if there was a change to actual filters
430 this.updateChangesList();
432 this.uriProcessor
.updateURL( params
);
437 * Check whether the default values of the filters are all false.
439 * @return {boolean} Defaults are all false
441 Controller
.prototype.areDefaultsEmpty = function () {
442 return $.isEmptyObject( this._getDefaultParams() );
446 * Empty all selected filters
448 Controller
.prototype.emptyFilters = function () {
449 var highlightedFilterNames
= this.filtersModel
.getHighlightedItems()
450 .map( function ( filterItem
) { return { name
: filterItem
.getName() }; } );
452 if ( this.applyParamChange( {} ) ) {
453 // Only update the changes list if there was a change to actual filters
454 this.updateChangesList();
456 this.uriProcessor
.updateURL();
459 if ( highlightedFilterNames
) {
460 this._trackHighlight( 'clearAll', highlightedFilterNames
);
465 * Update the selected state of a filter
467 * @param {string} filterName Filter name
468 * @param {boolean} [isSelected] Filter selected state
470 Controller
.prototype.toggleFilterSelect = function ( filterName
, isSelected
) {
471 var filterItem
= this.filtersModel
.getItemByName( filterName
);
474 // If no filter was found, break
478 isSelected
= isSelected
=== undefined ? !filterItem
.isSelected() : isSelected
;
480 if ( filterItem
.isSelected() !== isSelected
) {
481 this.filtersModel
.toggleFilterSelected( filterName
, isSelected
);
483 this.updateChangesList();
485 // Check filter interactions
486 this.filtersModel
.reassessFilterInteractions( filterItem
);
491 * Clear both highlight and selection of a filter
493 * @param {string} filterName Name of the filter item
495 Controller
.prototype.clearFilter = function ( filterName
) {
496 var filterItem
= this.filtersModel
.getItemByName( filterName
),
497 isHighlighted
= filterItem
.isHighlighted(),
498 isSelected
= filterItem
.isSelected();
500 if ( isSelected
|| isHighlighted
) {
501 this.filtersModel
.clearHighlightColor( filterName
);
502 this.filtersModel
.toggleFilterSelected( filterName
, false );
505 // Only update the changes list if the filter changed
506 // its selection state. If it only changed its highlight
508 this.updateChangesList();
511 this.filtersModel
.reassessFilterInteractions( filterItem
);
513 // Log filter grouping
514 this.trackFilterGroupings( 'removefilter' );
517 if ( isHighlighted
) {
518 this._trackHighlight( 'clear', filterName
);
523 * Toggle the highlight feature on and off
525 Controller
.prototype.toggleHighlight = function () {
526 this.filtersModel
.toggleHighlight();
527 this.uriProcessor
.updateURL();
529 if ( this.filtersModel
.isHighlightEnabled() ) {
530 mw
.hook( 'RcFilters.highlight.enable' ).fire();
535 * Toggle the namespaces inverted feature on and off
537 Controller
.prototype.toggleInvertedNamespaces = function () {
538 this.filtersModel
.toggleInvertedNamespaces();
540 this.filtersModel
.getFiltersByView( 'namespaces' ).filter(
541 function ( filterItem
) { return filterItem
.isSelected(); }
544 // Only re-fetch results if there are namespace items that are actually selected
545 this.updateChangesList();
547 this.uriProcessor
.updateURL();
552 * Set the value of the 'showlinkedto' parameter
553 * @param {boolean} value
555 Controller
.prototype.setShowLinkedTo = function ( value
) {
556 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' ),
557 showLinkedToItem
= this.filtersModel
.getGroup( 'toOrFrom' ).getItemByParamName( 'showlinkedto' );
559 this.filtersModel
.toggleFilterSelected( showLinkedToItem
.getName(), value
);
560 this.uriProcessor
.updateURL();
561 // reload the results only when target is set
562 if ( targetItem
.getValue() ) {
563 this.updateChangesList();
568 * Set the target page
569 * @param {string} page
571 Controller
.prototype.setTargetPage = function ( page
) {
572 var targetItem
= this.filtersModel
.getGroup( 'page' ).getItemByParamName( 'target' );
573 targetItem
.setValue( page
);
574 this.uriProcessor
.updateURL();
575 this.updateChangesList();
579 * Set the highlight color for a filter item
581 * @param {string} filterName Name of the filter item
582 * @param {string} color Selected color
584 Controller
.prototype.setHighlightColor = function ( filterName
, color
) {
585 this.filtersModel
.setHighlightColor( filterName
, color
);
586 this.uriProcessor
.updateURL();
587 this._trackHighlight( 'set', { name
: filterName
, color
: color
} );
591 * Clear highlight for a filter item
593 * @param {string} filterName Name of the filter item
595 Controller
.prototype.clearHighlightColor = function ( filterName
) {
596 this.filtersModel
.clearHighlightColor( filterName
);
597 this.uriProcessor
.updateURL();
598 this._trackHighlight( 'clear', filterName
);
602 * Enable or disable live updates.
603 * @param {boolean} enable True to enable, false to disable
605 Controller
.prototype.toggleLiveUpdate = function ( enable
) {
606 this.changesListModel
.toggleLiveUpdate( enable
);
607 if ( this.changesListModel
.getLiveUpdate() && this.changesListModel
.getNewChangesExist() ) {
608 this.updateChangesList( null, this.LIVE_UPDATE
);
613 * Set a timeout for the next live update.
616 Controller
.prototype._scheduleLiveUpdate = function () {
617 setTimeout( this._doLiveUpdate
.bind( this ), this.pollingRate
* 1000 );
621 * Perform a live update.
624 Controller
.prototype._doLiveUpdate = function () {
625 if ( !this._shouldCheckForNewChanges() ) {
626 // skip this turn and check back later
627 this._scheduleLiveUpdate();
631 this._checkForNewChanges()
632 .then( function ( statusCode
) {
633 // no result is 204 with the 'peek' param
635 var newChanges
= statusCode
=== 200;
637 if ( !this._shouldCheckForNewChanges() ) {
638 // by the time the response is received,
639 // it may not be appropriate anymore
643 // 205 is the status code returned from server when user's logged in/out
644 // status is not matching while fetching live update changes.
645 // This works only on Recent Changes page. For WL, look _extractChangesListInfo.
647 if ( statusCode
=== 205 ) {
648 location
.reload( false );
653 if ( this.changesListModel
.getLiveUpdate() ) {
654 return this.updateChangesList( null, this.LIVE_UPDATE
);
656 this.changesListModel
.setNewChangesExist( true );
660 .always( this._scheduleLiveUpdate
.bind( this ) );
664 * @return {boolean} It's appropriate to check for new changes now
667 Controller
.prototype._shouldCheckForNewChanges = function () {
668 return !document
.hidden
&&
669 !this.filtersModel
.hasConflict() &&
670 !this.changesListModel
.getNewChangesExist() &&
671 !this.updatingChangesList
&&
672 this.changesListModel
.getNextFrom();
676 * Check if new changes, newer than those currently shown, are available
678 * @return {jQuery.Promise} Promise object that resolves with a bool
679 * specifying if there are new changes or not
683 Controller
.prototype._checkForNewChanges = function () {
686 peek
: 1, // bypasses ChangesList specific UI
687 from: this.changesListModel
.getNextFrom(),
688 isAnon
: mw
.user
.isAnon()
690 return this._queryChangesList( 'liveUpdate', params
).then(
698 * Show the new changes
700 * @return {jQuery.Promise} Promise object that resolves after
701 * fetching and showing the new changes
703 Controller
.prototype.showNewChanges = function () {
704 return this.updateChangesList( null, this.SHOW_NEW_CHANGES
);
708 * Save the current model state as a saved query
710 * @param {string} [label] Label of the saved query
711 * @param {boolean} [setAsDefault=false] This query should be set as the default
713 Controller
.prototype.saveCurrentQuery = function ( label
, setAsDefault
) {
715 this.savedQueriesModel
.addNewQuery(
716 label
|| mw
.msg( 'rcfilters-savedqueries-defaultlabel' ),
717 this.filtersModel
.getCurrentParameterState( true ),
722 this._saveSavedQueries();
726 * Remove a saved query
728 * @param {string} queryID Query id
730 Controller
.prototype.removeSavedQuery = function ( queryID
) {
731 this.savedQueriesModel
.removeQuery( queryID
);
733 this._saveSavedQueries();
737 * Rename a saved query
739 * @param {string} queryID Query id
740 * @param {string} newLabel New label for the query
742 Controller
.prototype.renameSavedQuery = function ( queryID
, newLabel
) {
743 var queryItem
= this.savedQueriesModel
.getItemByID( queryID
);
746 queryItem
.updateLabel( newLabel
);
748 this._saveSavedQueries();
752 * Set a saved query as default
754 * @param {string} queryID Query Id. If null is given, default
757 Controller
.prototype.setDefaultSavedQuery = function ( queryID
) {
758 this.savedQueriesModel
.setDefault( queryID
);
759 this._saveSavedQueries();
765 * @param {string} queryID Query id
767 Controller
.prototype.applySavedQuery = function ( queryID
) {
768 var currentMatchingQuery
,
769 params
= this.savedQueriesModel
.getItemParams( queryID
);
771 currentMatchingQuery
= this.findQueryMatchingCurrentState();
774 currentMatchingQuery
&&
775 currentMatchingQuery
.getID() === queryID
777 // If the query we want to load is the one that is already
778 // loaded, don't reload it
782 if ( this.applyParamChange( params
) ) {
783 // Update changes list only if there was a difference in filter selection
784 this.updateChangesList();
786 this.uriProcessor
.updateURL( params
);
789 // Log filter grouping
790 this.trackFilterGroupings( 'savedfilters' );
794 * Check whether the current filter and highlight state exists
795 * in the saved queries model.
797 * @return {mw.rcfilters.dm.SavedQueryItemModel} Matching item model
799 Controller
.prototype.findQueryMatchingCurrentState = function () {
800 return this.savedQueriesModel
.findMatchingQuery(
801 this.filtersModel
.getCurrentParameterState( true )
806 * Save the current state of the saved queries model with all
807 * query item representation in the user settings.
809 Controller
.prototype._saveSavedQueries = function () {
810 var stringified
, oldPrefValue
,
811 backupPrefName
= this.savedQueriesPreferenceName
+ '-versionbackup',
812 state
= this.savedQueriesModel
.getState();
815 stringified
= JSON
.stringify( state
);
817 if ( byteLength( stringified
) > 65535 ) {
818 // Sanity check, since the preference can only hold that.
822 if ( !this.wereSavedQueriesSaved
&& this.savedQueriesModel
.isConverted() ) {
823 // The queries were converted from the previous version
824 // Keep the old string in the [prefname]-versionbackup
825 oldPrefValue
= mw
.user
.options
.get( this.savedQueriesPreferenceName
);
827 // Save the old preference in the backup preference
828 new mw
.Api().saveOption( backupPrefName
, oldPrefValue
);
829 // Update the preference for this session
830 mw
.user
.options
.set( backupPrefName
, oldPrefValue
);
833 // Save the preference
834 new mw
.Api().saveOption( this.savedQueriesPreferenceName
, stringified
);
835 // Update the preference for this session
836 mw
.user
.options
.set( this.savedQueriesPreferenceName
, stringified
);
838 // Tag as already saved so we don't do this again
839 this.wereSavedQueriesSaved
= true;
843 * Update sticky preferences with current model state
845 Controller
.prototype.updateStickyPreferences = function () {
846 // Update default sticky values with selected, whether they came from
847 // the initial defaults or from the URL value that is being normalized
848 this.updateDaysDefault( this.filtersModel
.getGroup( 'days' ).findSelectedItems()[ 0 ].getParamName() );
849 this.updateLimitDefault( this.filtersModel
.getGroup( 'limit' ).findSelectedItems()[ 0 ].getParamName() );
851 // TODO: Make these automatic by having the model go over sticky
852 // items and update their default values automatically
856 * Update the limit default value
858 * @param {number} newValue New value
860 Controller
.prototype.updateLimitDefault = function ( newValue
) {
861 this.updateNumericPreference( this.limitPreferenceName
, newValue
);
865 * Update the days default value
867 * @param {number} newValue New value
869 Controller
.prototype.updateDaysDefault = function ( newValue
) {
870 this.updateNumericPreference( this.daysPreferenceName
, newValue
);
874 * Update the group by page default value
876 * @param {boolean} newValue New value
878 Controller
.prototype.updateGroupByPageDefault = function ( newValue
) {
879 this.updateNumericPreference( 'usenewrc', Number( newValue
) );
883 * Update the collapsed state value
885 * @param {boolean} isCollapsed Filter area is collapsed
887 Controller
.prototype.updateCollapsedState = function ( isCollapsed
) {
888 this.updateNumericPreference( this.collapsedPreferenceName
, Number( isCollapsed
) );
892 * Update a numeric preference with a new value
894 * @param {string} prefName Preference name
895 * @param {number|string} newValue New value
897 Controller
.prototype.updateNumericPreference = function ( prefName
, newValue
) {
898 // FIXME: $.isNumeric is deprecated
899 // eslint-disable-next-line no-jquery/no-is-numeric
900 if ( !$.isNumeric( newValue
) ) {
904 newValue
= Number( newValue
);
906 if ( mw
.user
.options
.get( prefName
) !== newValue
) {
907 // Save the preference
908 new mw
.Api().saveOption( prefName
, newValue
);
909 // Update the preference for this session
910 mw
.user
.options
.set( prefName
, newValue
);
915 * Synchronize the URL with the current state of the filters
916 * without adding an history entry.
918 Controller
.prototype.replaceUrl = function () {
919 this.uriProcessor
.updateURL();
923 * Update filter state (selection and highlighting) based
924 * on current URL values.
926 * @param {boolean} [fetchChangesList=true] Fetch new results into the changes
927 * list based on the updated model.
929 Controller
.prototype.updateStateFromUrl = function ( fetchChangesList
) {
930 fetchChangesList
= fetchChangesList
=== undefined ? true : !!fetchChangesList
;
932 this.uriProcessor
.updateModelBasedOnQuery();
934 // Update the sticky preferences, in case we received a value
936 this.updateStickyPreferences();
938 // Only update and fetch new results if it is requested
939 if ( fetchChangesList
) {
940 this.updateChangesList();
945 * Update the list of changes and notify the model
947 * @param {Object} [params] Extra parameters to add to the API call
948 * @param {string} [updateMode='filterChange'] One of 'filterChange', 'liveUpdate', 'showNewChanges', 'markSeen'
949 * @return {jQuery.Promise} Promise that is resolved when the update is complete
951 Controller
.prototype.updateChangesList = function ( params
, updateMode
) {
952 updateMode
= updateMode
=== undefined ? this.FILTER_CHANGE
: updateMode
;
954 if ( updateMode
=== this.FILTER_CHANGE
) {
955 this.uriProcessor
.updateURL( params
);
957 if ( updateMode
=== this.FILTER_CHANGE
|| updateMode
=== this.SHOW_NEW_CHANGES
) {
958 this.changesListModel
.invalidate();
960 this.changesListModel
.setNewChangesExist( false );
961 this.updatingChangesList
= true;
962 return this._fetchChangesList()
965 function ( pieces
) {
966 var $changesListContent
= pieces
.changes
,
967 $fieldset
= pieces
.fieldset
;
968 this.changesListModel
.update(
971 pieces
.noResultsDetails
,
973 // separator between old and new changes
974 updateMode
=== this.SHOW_NEW_CHANGES
|| updateMode
=== this.LIVE_UPDATE
977 // Do nothing for failure
979 .always( function () {
980 this.updatingChangesList
= false;
985 * Get an object representing the default parameter state, whether
986 * it is from the model defaults or from the saved queries.
988 * @return {Object} Default parameters
990 Controller
.prototype._getDefaultParams = function () {
991 if ( this.savedQueriesModel
.getDefault() ) {
992 return this.savedQueriesModel
.getDefaultParams();
994 return this.filtersModel
.getDefaultParams();
999 * Query the list of changes from the server for the current filters
1001 * @param {string} counterId Id for this request. To allow concurrent requests
1002 * not to invalidate each other.
1003 * @param {Object} [params={}] Parameters to add to the query
1005 * @return {jQuery.Promise} Promise object resolved with { content, status }
1007 Controller
.prototype._queryChangesList = function ( counterId
, params
) {
1008 var uri
= this.uriProcessor
.getUpdatedUri(),
1009 stickyParams
= this.filtersModel
.getStickyParamsValues(),
1013 params
= params
|| {};
1014 params
.action
= 'render'; // bypasses MW chrome
1016 uri
.extend( params
);
1018 this.requestCounter
[ counterId
] = this.requestCounter
[ counterId
] || 0;
1019 requestId
= ++this.requestCounter
[ counterId
];
1020 latestRequest = function () {
1021 return requestId
=== this.requestCounter
[ counterId
];
1024 // Sticky parameters override the URL params
1025 // this is to make sure that whether we represent
1026 // the sticky params in the URL or not (they may
1027 // be normalized out) the sticky parameters are
1028 // always being sent to the server with their
1029 // current/default values
1030 uri
.extend( stickyParams
);
1032 return $.ajax( uri
.toString(), { contentType
: 'html' } )
1034 function ( content
, message
, jqXHR
) {
1035 if ( !latestRequest() ) {
1036 return $.Deferred().reject();
1040 status
: jqXHR
.status
1043 // RC returns 404 when there is no results
1044 function ( jqXHR
) {
1045 if ( latestRequest() ) {
1046 return $.Deferred().resolve(
1048 content
: jqXHR
.responseText
,
1049 status
: jqXHR
.status
1058 * Fetch the list of changes from the server for the current filters
1060 * @return {jQuery.Promise} Promise object that will resolve with the changes list
1063 Controller
.prototype._fetchChangesList = function () {
1064 return this._queryChangesList( 'updateChangesList' )
1069 // Status code 0 is not HTTP status code,
1070 // but is valid value of XMLHttpRequest status.
1071 // It is used for variety of network errors, for example
1072 // when an AJAX call was cancelled before getting the response
1073 if ( data
&& data
.status
=== 0 ) {
1075 changes
: 'NO_RESULTS',
1076 // We need empty result set, to avoid exceptions because of undefined value
1078 noResultsDetails
: 'NO_RESULTS_NETWORK_ERROR'
1082 $parsed
= $( '<div>' ).append( $( $.parseHTML(
1083 data
? data
.content
: ''
1086 return this._extractChangesListInfo( $parsed
, data
.status
);
1092 * Track usage of highlight feature
1094 * @param {string} action
1095 * @param {Array|Object|string} filters
1097 Controller
.prototype._trackHighlight = function ( action
, filters
) {
1098 filters
= typeof filters
=== 'string' ? { name
: filters
} : filters
;
1099 filters
= !Array
.isArray( filters
) ? [ filters
] : filters
;
1101 'event.ChangesListHighlights',
1105 userId
: mw
.user
.getId()
1111 * Track filter grouping usage
1113 * @param {string} action Action taken
1115 Controller
.prototype.trackFilterGroupings = function ( action
) {
1116 var controller
= this,
1117 rightNow
= new Date().getTime(),
1118 randomIdentifier
= String( mw
.user
.sessionId() ) + String( rightNow
) + String( Math
.random() ),
1119 // Get all current filters
1120 filters
= this.filtersModel
.findSelectedItems().map( function ( item
) {
1121 return item
.getName();
1124 action
= action
|| 'filtermenu';
1126 // Check if these filters were the ones we just logged previously
1127 // (Don't log the same grouping twice, in case the user opens/closes)
1128 // the menu without action, or with the same result
1130 // Only log if the two arrays are different in size
1131 filters
.length
!== this.prevLoggedItems
.length
||
1132 // Or if any filters are not the same as the cached filters
1133 filters
.some( function ( filterName
) {
1134 return controller
.prevLoggedItems
.indexOf( filterName
) === -1;
1136 // Or if any cached filters are not the same as given filters
1137 this.prevLoggedItems
.some( function ( filterName
) {
1138 return filters
.indexOf( filterName
) === -1;
1141 filters
.forEach( function ( filterName
) {
1143 'event.ChangesListFilterGrouping',
1146 groupIdentifier
: randomIdentifier
,
1148 userId
: mw
.user
.getId()
1153 // Cache the filter names
1154 this.prevLoggedItems
= filters
;
1159 * Apply a change of parameters to the model state, and check whether
1160 * the new state is different than the old state.
1162 * @param {Object} newParamState New parameter state to apply
1163 * @return {boolean} New applied model state is different than the previous state
1165 Controller
.prototype.applyParamChange = function ( newParamState
) {
1167 before
= this.filtersModel
.getSelectedState();
1169 this.filtersModel
.updateStateFromParams( newParamState
);
1171 after
= this.filtersModel
.getSelectedState();
1173 return !OO
.compare( before
, after
);
1177 * Mark all changes as seen on Watchlist
1179 Controller
.prototype.markAllChangesAsSeen = function () {
1180 var api
= new mw
.Api();
1181 api
.postWithToken( 'csrf', {
1183 action
: 'setnotificationtimestamp',
1184 entirewatchlist
: true
1185 } ).then( function () {
1186 this.updateChangesList( null, 'markSeen' );
1191 * Set the current search for the system.
1193 * @param {string} searchQuery Search query, including triggers
1195 Controller
.prototype.setSearch = function ( searchQuery
) {
1196 this.filtersModel
.setSearch( searchQuery
);
1200 * Switch the view by changing the search query trigger
1201 * without changing the search term
1203 * @param {string} view View to change to
1205 Controller
.prototype.switchView = function ( view
) {
1207 this.filtersModel
.getViewTrigger( view
) +
1208 this.filtersModel
.removeViewTriggers( this.filtersModel
.getSearch() )
1213 * Reset the search for a specific view. This means we null the search query
1214 * and replace it with the relevant trigger for the requested view
1216 * @param {string} [view='default'] View to change to
1218 Controller
.prototype.resetSearchForView = function ( view
) {
1219 view
= view
|| 'default';
1222 this.filtersModel
.getViewTrigger( view
)
1226 module
.exports
= Controller
;